package cn.cheqi.recovery.api.controller;


import cn.cheqi.recovery.api.dto.DataGridView;
import cn.cheqi.recovery.api.entity.Employee;
import cn.cheqi.recovery.api.mapper.EmployeeMapper;
import cn.cheqi.recovery.api.service.EmployeeService;
import cn.cheqi.recovery.api.upload.UploadService;
import cn.cheqi.recovery.api.utils.SysFileUtil;
import cn.cheqi.recovery.api.vo.EmployeeVO;
import cn.cheqi.recovery.api.vo.OrderVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  api接口员工前端控制器
 * </p>
 *
 * @author Robin
 * @since 2020-02-23
 */
@RestController("apiEmployeeController")
@RequestMapping("/api/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UploadService uploadService;

    @Value("${aliyun.oss.EmpSave}")
    private String EmpSave;

    /**
     * api接口加载所有员工信息
     * @param employeeVO
     * @return
     */
    @RequestMapping("/loadAllEmployees")
    public DataGridView loadAllEmployees(EmployeeVO employeeVO){
        IPage<Employee> page = new Page<>(employeeVO.getPage(),employeeVO.getLimit());
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        //获取模糊查询的条件
        //员工编号
        Long empId = employeeVO.getEmpId();
        //员工姓名
        String empName = employeeVO.getEmpName();
        //员工联系方式
        String empPhone = employeeVO.getEmpPhone();
        //清除模糊查询三个条件里的空格
        if (empId != null){
            wrapper.like("emp_id",empId);
        }
        if (!StringUtils.isBlank(empName)){
            String newEmpName = empName.replace(" ", "");
            wrapper.like(newEmpName != null,"emp_name",newEmpName);
        }
        if (!StringUtils.isBlank(empPhone)){
            String newEmpPhone = empPhone.replace(" ", "");
            wrapper.like(newEmpPhone != null, "emp_phone",empPhone);
        }
        wrapper.orderByDesc("emp_id");
        employeeService.page(page,wrapper);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",page.getRecords().size());
        map.put("zpage",page.getPages());
        map.put("page",page.getCurrent());
        map.put("list",page.getRecords());
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * api接口通过员工ID查出员工详情,通过员工ID多表联查查出员工所属小区
     * @param employeeVO
     * @return
     */
    @RequestMapping("/detailEmpById")
    public DataGridView detailEmpById(EmployeeVO employeeVO){
        if (employeeService.getById(employeeVO.getEmpId()) == null){
            return new DataGridView(1,"该员工信息不存在","");
        }
        EmployeeVO empVO = employeeMapper.findEmpDetailById(employeeVO.getEmpId());
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        dataGridView.setData(empVO);
        return dataGridView;
    }

    /**
     * api接口添加员工
     * @param employeeVO
     * @return
     */
    @PostMapping("/addEmployee")
    @Transactional
    public DataGridView addEmployee(EmployeeVO employeeVO){
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("emp_phone",employeeVO.getEmpPhone());
        if (employeeService.count(wrapper) > 0){
            return new DataGridView(1,"该手机号已被注册","");
        }
        try {
            //设置默认的图片路径
            employeeVO.setEmpPic("https://rob1n-bucket.oss-cn-shenzhen.aliyuncs.com/recovery/employee/default/default.jpg");
            employeeService.save(employeeVO);
            return new DataGridView(0,"添加成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"添加失败",null);
        }
    }

    /**
     * api接口通过员工ID编辑员工信息
     * @param employeeVO
     * @return
     */
    @PostMapping("/editEmployee")
    @Transactional
    public DataGridView editEmployeeById(EmployeeVO employeeVO){
        //判断该员工是否存在
        Employee employee = employeeService.getById(employeeVO.getEmpId());
        if (employee == null){
            return new DataGridView(1,"该员工信息不存在","");
        }
        //判断编辑的信息是否为空
        if (employeeVO.getEmpName()==null&&employeeVO.getEmpPhone()==null&&employeeVO.getEmpAge()==null&&employeeVO.getEmpPassword()==null&&
            employeeVO.getChargeArea()==null&&employeeVO.getCommunityId()==null){
            return new DataGridView(1,"您所输入的编辑信息不能为空","");
        }
        try {
            employeeService.updateById(employeeVO);
            return new DataGridView(0,"修改成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataGridView(1,"修改失败",null);
        }
    }

    /**
     * api接口通过员工ID删除员工
     * @param employeeVO
     * @return
     */
    @PostMapping("/deleteEmpById")
    @Transactional
    public DataGridView deleteEmployeeById(EmployeeVO employeeVO){
        Employee employee = employeeService.getById(employeeVO.getEmpId());
        if (employee == null){
            return new DataGridView(1,"该员工信息不存在","");
        }
        try {
            //判断用户的头像图片是否为默认图片,若不是则删除
            Long empId = employeeVO.getEmpId();
            String avatarUrl = employeeService.getById(empId).getEmpPic();
            if (!avatarUrl.equals(SysFileUtil.Default_Img_Path)){
                SysFileUtil.removeOldFile(avatarUrl);
            }
            employeeService.removeById(employeeVO.getEmpId());
            return new DataGridView(0,"删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataGridView(1,"删除失败",null);
        }
    }


    /**
     * 通过用户ID更新用户的头像
     * @param employeeVO
     * @param file 上传的用户头像
     * @return
     */
    @PostMapping("/editEmpPicById")
    @Transactional
    public DataGridView editEmpPicById(@RequestParam("file")MultipartFile file, EmployeeVO employeeVO){
        //判断该用户是否存在
        Employee employee = employeeService.getById(employeeVO.getEmpId());
        if (employee == null){
            return new DataGridView(1,"您所编辑的员工不存在","");
        }

        //如果满足上述条件则更新头像
        try{
            DataGridView dataGridView = uploadService.uploadImg(file,EmpSave);
            //判断回显的data是否为空,为空的话则不管,否则更新图片
            if (dataGridView.getData() != null && dataGridView.getData() != ""){
                employeeVO.setEmpPic((String) dataGridView.getData());
                employeeService.updateById(employeeVO);
            }
            return dataGridView;
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"头像更新失败","");
        }
    }

    /**
     * api接口通过员工ID查出该员工的所有订单详情
     * @param employeeVO
     * @return
     */
    @PostMapping("/findOrdersByEmpId")
    public DataGridView findOrdersByEmpId(EmployeeVO employeeVO){
        Employee employee = employeeService.getById(employeeVO.getEmpId());
        if (employee == null){
            return new DataGridView(1,"该员工信息不存在","");
        }
        //分页条件
        Page<Employee> page = new Page<>();
        if (employeeVO.getPage() != null && employeeVO.getLimit() != null){
            page.setPages(employeeVO.getPage());
            page.setSize(employeeVO.getLimit());
        }
        List<OrderVO> orderVOS = employeeMapper.findOrdersByEmpId(employeeVO.getEmpId(),page);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",orderVOS.size());
        map.put("page",page.getCurrent());
        map.put("zpage",page.getPages());
        map.put("list",orderVOS);
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * 添加员工的身份证验证图片接口
     * @param file 上传的身份证照片
     * @return
     */
    @PostMapping("/uploadEmpIdentityPic")
    @Transactional
    public DataGridView uploadUserIdentityPic(@RequestParam("identityPic")MultipartFile file){
        try{
            DataGridView dataGridView = uploadService.uploadImg(file,EmpSave);
            return dataGridView;
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"身份证图片上传失败","");
        }
    }


    /**
     * 把上传好的身份证图片绑定员工ID更新提交员工信息
     * @param employeeVO
     * @return
     */
    @PostMapping("/addEmpIdentityPic")
    @Transactional
    public DataGridView addUserIdentityPic(EmployeeVO employeeVO){
        //判断该用户是否存在
        Employee employee = employeeService.getById(employeeVO.getEmpId());
        if (employee == null){
            return new DataGridView(1,"您所编辑的员工信息不存在","");
        }
        //取出每个员工身份证的照片链接
        String identityPic = employeeVO.getIdentityPic();
        if (identityPic.equals("")){
            return new DataGridView(1,"请先上传图片","");
        }
        //如果满足上述条件则提交身份证照片到数据库
        try{
            UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("emp_id",employeeVO.getEmpId());
            Employee updateEmp = new Employee();
            updateEmp.setIdentityPic(identityPic);
            employeeService.update(updateEmp,updateWrapper);
            return new DataGridView(0,"提交成功","");
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"提交失败","");
        }
    }

}

